//
//  DebugUserDefaultController.m
//  YK_DebugManager
//
//  Created by edward on 2021/1/13.
//

#import "DebugUserDefaultController.h"

@interface DebugUserDefaultController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating>
///
@property(nonatomic,strong) UITableView *tableView;

@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic, strong) NSArray *searchResult;

@end

@implementation DebugUserDefaultController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
}
- (void)setupUI
{
    self.title = @"UserDefault";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(clearDatas)];
    
    [self.view addSubview:self.tableView];
}
#pragma mark -tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return [[NSUserDefaults standardUserDefaults].dictionaryRepresentation allKeys].count;
    if (self.searchController.active) {
        return self.searchResult.count;
    }
    return [[NSUserDefaults standardUserDefaults].dictionaryRepresentation allKeys].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(UITableViewCell.class)];
    //当需要用到detailTextLabel的时候需要注释掉注册cell的方法，这时候就需要对cell进行判空处理
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:NSStringFromClass(UITableViewCell.class)];
        cell.backgroundColor = UIColor.clearColor;
        cell.contentView.backgroundColor = UIColor.clearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSString *key = [[NSUserDefaults standardUserDefaults].dictionaryRepresentation allKeys][indexPath.row];
    if (self.searchController.active) {
        key = self.searchResult[indexPath.row];
    }
    id value = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    NSString *valueString = [NSString stringWithFormat:@"%@",value];
    valueString = [[valueString stringByReplacingOccurrencesOfString:@"\r" withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    cell.textLabel.text = key;
    cell.detailTextLabel.text = valueString;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = [[NSUserDefaults standardUserDefaults].dictionaryRepresentation allKeys];
    
    if (self.searchController.active) {
        arr = self.searchResult;
    }
    NSString *key = arr[indexPath.row];
    
    id value = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    NSString *string = [NSString stringWithFormat:@"%@",value];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:key message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:cancelAction];
    if(self.searchController.active)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    [self presentViewController:alertController animated:YES completion:nil];
}
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, debug_top_Height, self.view.bounds.size.width, self.view.bounds.size.height - debug_top_Height - (self.view.safeAreaInsets.bottom)) style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 85;
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.backgroundColor = UIColor.clearColor;
        tableView.tableHeaderView = self.searchController.searchBar;
        //当需要使用到detailTextLabel的时候不需要注册
//        [tableView registerClass:UITableViewCell.class forCellReuseIdentifier:NSStringFromClass(UITableViewCell.class)];
        _tableView = tableView;
    }
    return _tableView;
}

- (void)clearDatas {
    
    [self.view endEditing:YES];
    
    __weak typeof(self) weakself = self;
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清理所有缓存数据" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:NSBundle.mainBundle.bundleIdentifier];
        [weakself.tableView reloadData];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *inputStr = searchController.searchBar.text;
    NSMutableArray *arr = [NSMutableArray array];
//    for (DebugNetWorkModel *record in [DebugNetWorkManager sharedInstance].records) {
//        if ([[record.url lowercaseString] containsString:[inputStr lowercaseString]]) {
//            //containsString（包含字符串）
//            [arr addObject:record];
//        }
//    }
    for (NSString *key in [[NSUserDefaults standardUserDefaults].dictionaryRepresentation allKeys]) {
        if ([[key lowercaseString] containsString:[inputStr lowercaseString]]) {
            [arr addObject:key];
        }
    }
    self.searchResult = arr;
    [self.tableView reloadData];
}

- (UISearchController *)searchController
{
    if (!_searchController) {
        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;
    }
    return _searchController;
}
- (NSArray *)searchResult
{
    if(!_searchResult)
    {
        _searchResult = [NSArray array];
    }
    return _searchResult;
}

- (void)dealloc
{
    
}

@end
